package xzit.gcxy.xxhzx.zhh.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import xzit.gcxy.xxhzx.zhh.client.Client;
import xzit.gcxy.xxhzx.zhh.client.TreeNode;
import xzit.gcxy.xxhzx.zhh.common.AjaxJson;
import xzit.gcxy.xxhzx.zhh.common.ContextHolderUtils;
import xzit.gcxy.xxhzx.zhh.common.ResourceUtil;
import xzit.gcxy.xxhzx.zhh.common.SystemConstant;
import xzit.gcxy.xxhzx.zhh.entity.APPNavigatorVO;
import xzit.gcxy.xxhzx.zhh.entity.ManagedAccountVO;
import xzit.gcxy.xxhzx.zhh.manager.ClientManager;
import xzit.gcxy.xxhzx.zhh.service.SystemService;

@Controller
@RequestMapping("/loginController")
public class LoginController {

	private static final Logger logger = Logger.getLogger(LoginController.class);

	@Autowired
	private SystemService systemService;

	/**
	 * 登陆页
	 * 
	 * @param error
	 * @param model
	 * @return
	 */
	@RequestMapping(params = "login")
	public ModelAndView login(HttpServletRequest request) {
		return new ModelAndView("system/login");
	}

	@RequestMapping(params = "home")
	public ModelAndView home(HttpServletRequest request) {
		return new ModelAndView("system/home");
	}

	/**
	 * 退出系统
	 * 
	 * @param user
	 * @param req
	 * @return
	 */
	@RequestMapping(params = "logout")
	public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = ContextHolderUtils.getSession();
		ClientManager.getInstance().removeClinet(session.getId());
		session.invalidate();
		ModelAndView modelAndView = new ModelAndView(new RedirectView("loginController.do?login"));

		return modelAndView;
	}

	@RequestMapping(params = "doLogin")
	public ModelAndView doLogin(HttpServletRequest req) {
		ModelAndView mav = new ModelAndView("system/main");
		HttpSession session = ContextHolderUtils.getSession();
		Client client = ClientManager.getInstance().getClient(session.getId());
		req.setAttribute("username", client.getUser().getUsername());
		req.setAttribute("rolename", "管理员");
		return mav;
	}

	@RequestMapping(params = "doCheck")
	@ResponseBody
	public AjaxJson doCheck(HttpServletRequest req, String username, String password, String captcha) {
		HttpSession session = ContextHolderUtils.getSession();
		AjaxJson j = new AjaxJson();

		if (!captcha.equalsIgnoreCase(String.valueOf(session.getAttribute(SystemConstant.KEY_CAPTCHA)))) {
			j.setSuccess(false);
			j.setMsg("验证码错误!");
		} else {
			ManagedAccountVO user = new ManagedAccountVO();
			user.setUsername(username);
			user.setPassword(password);
			user = this.systemService.getUserByNameAndPassword(user);
			if (user == null) {
				j.setSuccess(false);
				j.setMsg("用户名或密码错误！");
				return j;
			}

			Client client = new Client();
			client.setIp(ResourceUtil.getIpAddr(req));
			client.setLogindatetime(new Date());
			client.setUser(user);
			ClientManager.getInstance().addClinet(session.getId(), client);
			if (user != null && user.getId() >= 0) {
				j.setSuccess(true);
				j.setMsg("登陆成功！");
			} else {
				j.setSuccess(false);
				j.setMsg("用户名或密码错误!");
			}

			logger.info(ResourceUtil.getIpAddr(req) + "    " + JSONObject.valueToString(j));
		}
		return j;
	}

	@RequestMapping(params = "getTreeMenu")
	@ResponseBody
	public String getTreeMenu(HttpServletRequest request) {
		APPNavigatorVO root = systemService.getAPPRootByNameAndPassword();
		APPNavigatorVO yingyong = root.getApps().get(0);
		APPNavigatorVO xitong = root.getApps().get(1);
		List<APPNavigatorVO> yyList = yingyong.getApps();
		List<APPNavigatorVO> xtList = xitong.getApps();
		List<APPNavigatorVO> total = new ArrayList();
		List<APPNavigatorVO> rootl = new ArrayList();
		rootl.add(root);
		total.add(root);
		total.add(yingyong);
		total.add(xitong);
		total.addAll(yyList);
		total.addAll(xtList);
		Client client = ResourceUtil.getClient();
		ManagedAccountVO user = client.getUser();
		//判断级别
		for (APPNavigatorVO vo : xtList) {
			if (vo.getLevel() > user.getLevel()) {
				total.remove(vo);
			}
		}

		return JSONObject.valueToString(resourceToTreeNode(rootl, total));
	}

	/**
	 * 将sysResource类型的数据集合转化为前端较好识别的TreeNode
	 * 
	 * @param resource
	 * @return
	 */
	private List<TreeNode> resourceToTreeNode(List<APPNavigatorVO> resource, List<APPNavigatorVO> userResource) {
		if (resource != null && !resource.isEmpty()) {
			List<TreeNode> ch = new ArrayList<TreeNode>();
			for (APPNavigatorVO rr : resource) {
				TreeNode node = new TreeNode();
				if (userResource.contains(rr)) {
					if (rr.getAppurl() == null) {
						node.setId(rr.getId());
					} else {
						node.setId(rr.getId());
					}
					node.setId(rr.getId());
					node.setState("open");
					node.setText(rr.getAppname());

					Map<String, Object> _temp = new HashMap<String, Object>();
					_temp.put("href", rr.getAppurl());
					node.setAttributes(_temp);

					ch.add(node);

				}
				node.setChildren(resourceToTreeNode(rr.getApps(), userResource));
			}

			return ch;
		}
		return Collections.emptyList();
	}
}
